$(function() {
	var listui = {};
	
	var getQueryUrl = function(container){
		return container.find('.listQueryUrl').val();
	}
	
	var getTableFields = function(container){
		return container.find('.listTableFields').val().split(',');
	}

	var getQueryFields = function(container){
		return container.find('.listQueryFields').val().split(',');
	}
	
	$('.tool-bottom').on('click', function() {
		var container = $(this).closest('.listui');
		var height = container.data('listui-query-div-height');
		if (container.find('.query').outerHeight(true) == height) {
			container.find(".query").animate({
				"height" : '40px'
			}, "slow");
			container.find('.tool-bottom>i').removeClass('icon-xiangshang').addClass('icon-xiangxia');
		} else {
			container.find(".query").animate({
				"height" : height + 'px'
			}, "slow");
			container.find('.tool-bottom>i').removeClass('icon-xiangxia').addClass('icon-xiangshang');
		}
	});

	var clearSortState = function(container) {
		container.find('table>thead>tr>th>i').removeClass('icon-xiaosanjiaodown icon-xiaosanjiaoup icon-sort-small').addClass('icon-sort-small');
		container.find('table>thead>tr>th').removeClass('sort desc asc');
	}

	$('.listui table>thead>tr>th>i').on('click', function() {
		var container = $(this).closest('.listui');
		if (!$(this).parent().hasClass('sort')) {
			clearSortState(container);
			$(this).parent().addClass('sort desc');
			$(this).removeClass('icon-sort-small').addClass('icon-xiaosanjiaodown');
		} else {
			if ($(this).parent().hasClass('desc')) {
				clearSortState(container);
				$(this).parent().addClass('sort asc');
				$(this).removeClass('icon-sort-small').addClass('icon-xiaosanjiaoup');
			} else {
				clearSortState(container);
				$(this).parent().addClass('sort desc');
				$(this).removeClass('icon-sort-small').addClass('icon-xiaosanjiaodown');
			}
		}
		refresh(container);
	});

	var refresh = function(container,pageIndex, isNotShowProgress70) {
		if (!isNotShowProgress70) {
			progress70();
		}
		var queryData = getQueryData(container);
		if (container.find('.sort').length > 0) {
			queryData.sortField = container.find('.sort').attr('data-field');
			queryData.sortType = container.find('.sort').hasClass('desc') ? "desc" : "asc";
		}
		if (pageIndex) {
			queryData.page = pageIndex;
		} else {
			queryData.page = container.find('.pager .active>a').text() || '1';
		}
		progress80();
		time = new Date().getTime();
		$.post(getQueryUrl(container) + '/listQuery', queryData, function(res) {
			time = new Date().getTime();
			progress90();
			refreshTable(container,res.list);
			refreshPagination(container,res.pageInfo);
			progress100();
			if(typeof(refreshEnd) == 'function'){
				refreshEnd(container);
			}
		});
	}
	listui.refresh = function(listuiID){
		var containers = $('.listui');
		if(containers.length == 1 ){
			refresh($(containers.get(0)));
		}else if(containers.length > 1 ){
			if(listuiID){
				refresh($('#'+listuiID));
			}else{
				throw Error("当前有多个listui，该方法的调用需要指定ID。");
			}
		}
	};
	
	var getQueryData = function(container){
		var queryData = {};
		$(getQueryFields(container)).each(function(index,key){
			queryData[key] = container.find('#' + key).val();
		});
		if(typeof(getCustomQueryData) == 'function'){
			var customQueryData = getCustomQueryData(container);
			if(customQueryData){
				$.extend(queryData,customQueryData);
			}
		}
		return queryData;
	}
	
	listui.getQueryData = function(listuiID){
		var containers = $('.listui');
		if(containers.length == 1 ){
			return getQueryData($(containers.get(0)));
		}else if(containers.length > 1 ){
			if(listuiID){
				return getQueryData($('#'+listuiID));
			}else{
				throw Error("当前有多个listui，该方法的调用需要指定ID。");
			}
		}
	};
	
	var underlineProp = function(tf){
		var newTF = "";
		var sign = false;
		for(var i=0;i<tf.length;i++){
			if(sign){
				newTF += tf.charAt(i).toUpperCase();
				sign = false;
				continue;
			}
			if(tf.charAt(i) == '_'){
				sign = true;
				continue;
			}
			newTF += tf.charAt(i);
		}
		return newTF;
	}

	var refreshTable = function(container,list) {
		container.find('.list-content-div table>tbody').empty();
		if (list) {
			$(list).each(function(index, obj) {
				var tr = $('<tr/>');
				tr.append($('<td/>').text(index + 1));
				
				$(getTableFields(container)).each(function(ci,tf){
					var tfNotUnderline = underlineProp(tf);//与后端框架vo采用相同的规则：下划线去掉后驼峰命名
					var cellVal = obj[tfNotUnderline];
					if(typeof(handleCellValue) == "function"){
						cellVal = handleCellValue(tfNotUnderline,cellVal,obj,container); // (列名，单元格值，行对象)
					}
					if(obj[tfNotUnderline] != null){
						tr.append($('<td/>').html(cellVal));
					}else
						tr.append($('<td/>').html(''));
				});
				var notShowOpColumn = container.find('.list-content-div .notShowOpColumn').val();
				if(notShowOpColumn != 'true'){
					if(typeof(handleOpRow) == "undefined"){
						tr.append($('<td/>').addClass('op').append($('<a/>', {
							"href" : "javascript:;",
							"data-id" : obj.id
						}).addClass('edit').text('编辑')).append($('<span/>').text('|')).append($('<a/>', {
							"href" : "javascript:;",
							"data-id" : obj.id
						}).addClass('del').text('删除')));
					}else{
						handleOpRow(tr,obj,container);
					}
				}
				container.find('.list-content-div table>tbody').append(tr);
			});
		}
	}

	$('.list-content-div table>tbody').delegate('tr>td>.edit', 'click', function() {
		var id = $(this).attr('data-id');
		var container = $(this).closest('.listui');
		if(id){
			if(typeof(editBill) == "function"){
				editBill(id,container);
			}else{
				location.href = 'http://' + location.hostname + container.find('.listQueryUrl').val() + '/edit/' + id;
			}
			
		}
	});

	$('.list-content-div .pager').delegate('li', 'click', function() {
		var container = $(this).closest('.listui');
		if ($(this).hasClass('active') || $(this).hasClass('disabled')) {
			return false;
		}
		var curText = $(this).find('a').text();
		var preIndex = container.find('.pager>.active>a').text();
		var curIndex;
		if (curText == '«') {
			curIndex = parseInt(preIndex) - 1;
		} else if (curText == '»') {
			curIndex = parseInt(preIndex) + 1;
		} else {
			curIndex = $(this).find('a').text();
		}
		container.find('.pager>li').removeClass('active');
		$(this).addClass('active');
		refresh(container,curIndex);
	});

	$('.list-content-div table>tbody').delegate('tr>td>.del', 'click', function() {
		var container = $(this).closest('.listui');
		if (confirm("确认删除该条信息吗？")) {
			var id = $(this).attr('data-id');
			progress70();
			$.getJSON(getQueryUrl(container) + '/delete/' + id, function(res) {
				if (res.state) {
					refresh(container,null, true);
				}else{
					alert('数据删除失败');
				}
			});
		}
	});

	var refreshPagination = function(container,pinfo) {
		var pager = container.find('.list-content-div .pager');
		pager.empty();
		if (pinfo && pinfo.pageIndexs) {
			$(pinfo.pageIndexs).each(function(index, obj) {
				var li = $('<li/>');
				if (obj["class"]) {
					li.addClass(obj["class"]);
				}
				li.append($('<a/>', {
					"href" : "javascript:;"
				}).text(obj.text));
				pager.append(li);
			});
		}
	}

	$('.btn-query').on('click', function() {
		var container = $(this).closest('.listui');
		refresh(container);
	});

	var progress70 = function() {
		$('#progress-ajax').removeClass('done').css('width', '0').show();
		if($.browser.msie && ($.browser.version == '8.0' || $.browser.version == '7.0' || $.browser.version == '6.0')){
			for(var v = 10; v <= 70 ; ){
				setTimeout(function(){
					$('#progress-ajax').css('width', v + "%");
				}, 10 * v);
				v += 10;
			}
		}else{
			$({
				property : 0
			}).animate({
				property : 70
			}, {
				duration : 1000,
				step : function() {
					var percentage = Math.round(this.property);
					$('#progress-ajax').css('width', percentage + "%");
				}
			});
		}
	}

	var progress80 = function() {
		if($.browser.msie && ($.browser.version == '8.0' || $.browser.version == '7.0' || $.browser.version == '6.0')){
			setTimeout(function(){
				$('#progress-ajax').css('width', "80%");
			}, 800);
		}else{
			$('#progress-ajax').css('width', "80%");
		}
	}
	var progress90 = function() {
		if($.browser.msie && ($.browser.version == '8.0' || $.browser.version == '7.0' || $.browser.version == '6.0')){
			setTimeout(function(){
				$('#progress-ajax').css('width', "90%");
			}, 900);
		}else{
			$('#progress-ajax').css('width', "90%");
		}
	}
	var progress100 = function() {
		if($.browser.msie && ($.browser.version == '8.0' || $.browser.version == '7.0' || $.browser.version == '6.0')){
			setTimeout(function(){
				$('#progress-ajax').css('width', "100%");
				$("#progress-ajax").addClass("done");
				$('#progress-ajax').css('width', "0");
			}, 1000);
		}else{
			$('#progress-ajax').css('width', "100%");
			$("#progress-ajax").addClass("done");
			$('#progress-ajax').css('width', "0");
		}
	}

	$(document).ready(function() {
		var containers = $('.listui');
		if(containers.length == 1 ){
			var container = $(containers.get(0));
			var height = container.find('.query').outerHeight(true);
			container.data('listui-query-div-height',height);
			refresh(container);
		}else if(containers.length > 1 ){
			containers.each(function(index,item){
				var container = $(item);
				var height = container.find('.query').outerHeight(true);
				container.data('listui-query-div-height',height);
				refresh(container);
				return false;
			});
		}
	});
	
	var userAgent = navigator.userAgent.toLowerCase();
    $.browser = {
        version: (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1],
        safari: /webkit/.test(userAgent),
        opera: /opera/.test(userAgent),
        msie: /msie/.test(userAgent) && !/opera/.test(userAgent),
        mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent)
    };
	
	window.listui = window["listui"] = listui;

});
